// ==================================================================================
// Shared Genomics Project MPI Codebase
// Version 1.0 30/04/2010
//
// (c) 2010 University of Manchester all rights reserved
//
// This file is distributed under the GNU General Public License, Version 2.  
// Please see the file COPYING.txt for more details
// ==================================================================================

/*!
\file
\brief Implementation of Boolean Array from binary file
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "boolfile.h"
#include "copyfile.h"

int boolfile_create_and_copy(BOOL *src, int nSrc, struct selected_options *ops, char *suffix) {
	BOOL jobDone = FALSE;
	FILE *out = NULL;
	char localFilepath[FILE_PATH_LENGTH], remoteFilepath[FILE_PATH_LENGTH];

	if (src == NULL || nSrc <= 0 || ops == NULL || suffix == NULL) return 0;
	else if (strlen(ops->szRunId) == 0 || strlen(suffix) == 0 || strlen(ops->ldir) == 0 || strlen(ops->rdir) == 0) return 0;
	
	sprintf(localFilepath, "%s%s%s", ops->ldir, ops->szRunId, suffix);
	sprintf(remoteFilepath, "%s%s%s", ops->rdir, ops->szRunId, suffix);

	out = fopen(localFilepath, "wb"); 
	if (out != NULL) {
		if (fwrite(&nSrc, sizeof(int), 1, out) == 1) {
			if (fwrite(src, sizeof(BOOL), nSrc, out) == nSrc) jobDone = TRUE;
		}
	}
	if (out != NULL) fclose(out);

	// Copy the local output file to central file store.
	if (jobDone) {
		jobDone = FALSE;
		if (copyAndDeleteFile(localFilepath, remoteFilepath)) jobDone = TRUE;
	}
	
	if (jobDone) return 1;
	else return 0;
}

BOOL* boolfile_read(struct selected_options *ops, char *suffix, int *nSize) {
	FILE *in = NULL;
	BOOL *data = NULL;
	char filepath[FILE_PATH_LENGTH];

	if (ops == NULL || suffix == NULL || nSize == NULL) return data;
	else if (strlen(ops->szRunId) == 0 || strlen(suffix) == 0 || strlen(ops->rdir) == 0) return data;
	
	*nSize = 0;
	sprintf(filepath, "%s%s%s", ops->rdir, ops->szRunId, suffix);
	in = fopen(filepath, "rb");
	if (in) {
		if(fread(nSize, sizeof(int), 1, in) == 1) {
			if (*nSize > 0) {
				data = (BOOL*) malloc(*(nSize) * sizeof(BOOL));
				if (data != NULL) {
					if (fread(data, sizeof(BOOL), *(nSize), in) != *nSize) {
						// Eeek, I/O failure.
						free(data);
						data = NULL;
						*nSize = 0;
					}
				}
			}
		}
		fclose(in);
	}

	return data;
}
